package com.heihei.mymusic.util.dto;

import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Map操作工具类
 *
 */
public class MapUtil {

	public static <T, K, U> Map<K, U> map(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, List<T> sourceList) {
		if (CollectionUtils.isEmpty(sourceList)) {
			return Collections.emptyMap();
		}
		return sourceList.stream().collect(Collectors.toMap(keyMapper, valueMapper));
	}

	public static <T, K> Map<K, T> map(Function<? super T, ? extends K> keyMapper, List<T> sourceList) {
		if (CollectionUtils.isEmpty(sourceList)) {
			return Collections.emptyMap();
		}
		return sourceList.stream().collect(Collectors.toMap(keyMapper, Function.identity()));
	}

	public static <T, R> List<R> mapList(Function<? super T, ? extends R> keyMapper, List<T> sourceList) {
		if (CollectionUtils.isEmpty(sourceList)) {
			return Collections.emptyList();
		}
		return sourceList.stream().map(keyMapper).collect(Collectors.toList());
	}

	public static <T> List<T> mapList(List<T> sourceList) {
		if (CollectionUtils.isEmpty(sourceList)) {
			return Collections.emptyList();
		}
		return sourceList.stream().map(Function.identity()).collect(Collectors.toList());
	}

	public static <T, K> Map<K, List<T>> group(Function<? super T, ? extends K> keyMapper, List<T> sourceList) {
		if (CollectionUtils.isEmpty(sourceList)) {
			return Collections.emptyMap();
		}
		return sourceList.stream().collect(Collectors.groupingBy(keyMapper));
	}

	/**
	 * 
	 * 方法描述  以keyMapper分组，组内元素为valueMapper返回值
	 *
	 */
	public static <T, K, U> Map<K, List<U>> group(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, List<T> sourceList) {
		if (CollectionUtils.isEmpty(sourceList)) {
			return Collections.emptyMap();
		}
		Map<K, List<U>> dd = sourceList.stream().collect(Collectors.groupingBy(keyMapper, HashMap::new, Collectors.mapping(valueMapper, Collectors.toList())));
		return dd;
	}

}
